<template>
  <span class="checkbox-select-wrapper">
      <el-select v-bind="$attrs" v-bind:checked="checkList" :value="selectLabel">
          <el-option 
            class="checkbox-select-option"
            :label="selectLabel" 
            :value="checkList" >
            <div @click.stop="() => {}">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group class="checkbox-select-group" v-model="checkList" @change="handleCheckedCitiesChange">
                    <el-checkbox 
                    v-for="item in options"
                    :key="item.value"
                    :label="item.value"
                    >{{item.label}}</el-checkbox>
                </el-checkbox-group>
            </div>
            </el-option>
      </el-select>
  </span>
</template>

<script>
export default {
    name:'CheckboxSelect',
    inheritAttrs: false,
    model: {
      prop:'checked',
      event: 'update'
    },
    props:{
        options:{
            type:Array,
            default:() => []
        }
    },
    data(){
        return {
            checkAll: false,
            isIndeterminate: false,
            checkList:[]
        }
    },
    computed:{
        selectLabel(){
            let label = '';
            if(this.checkAll){
                label = '全选'
            }else{
                this.options.forEach(item => {
                    if(this.checkList.findIndex(c => c == item.value) !== -1){
                        label += item.label + '/';
                    }
                })
                label = label.substring(0, label.length - 1);
            }
            return label;
        }
    },
    watch:{
        checkList(val){
            this.$emit('change', {value:val, checkAll:this.checkAll});
            this.$emit('update', val);
        }
    },
    mounted(){
        
    },
    methods:{
        //全选
        handleCheckAllChange(val) {
            this.checkList = val ? this.options.map(item => item.value) : [];
            this.isIndeterminate = false;
        },
        //选中状态改变
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.options.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.options.length;

        }
    }
}
</script>


<style lang="scss">
    .checkbox-select-option{
        height: auto;
        &.hover{
            background-color: transparent!important;
        }
    }
    .checkbox-select-group{
        display: flex;
        flex-direction: column;
    }
</style>

<style lang="scss" scoped>
    .checkbox-select-wrapper{
        
    }
</style>